let AliOSS = require("ali-oss");
import Utils from "./utils.js";
const OssFile = {
  /**设置文件路径 */
  getMaterials(fileN) {
    let date = new Date();
    let index = fileN.lastIndexOf(".");
    return `${date.getFullYear()}-${date.getMonth() + 1}/${hex_md5(
      fileN
    )}${date.getTime()}${fileN.substring(index, fileN.length)}`;
  },
  /**
   * 直接上传图片(dom)
   * @param file 文件
   * @param config sts接口返回的信息
   * @param basic  压缩属性0-1 {w,h,q}
   */
  uploadImage(file, config, basic = "") {
    let th = this;
    return new Promise(function(resolve, reject) {
      let str = th.getMaterials(file.name);
      let begin = async file => {
        let Obj = new AliOSS({
          //   region: "oss-cn-hangzhou",
          accessKeyId: config.accessKeyId,
          accessKeySecret: config.accessKeySecret,
          stsToken: config.securityToken,
          endpoint: "https://oss-cn-beijing.aliyuncs.com",
          bucket: config.bucket
        });
        try {
          let result = await Obj.put(str, file);
          resolve({
            executed: true,
            path: str
          });
        } catch (e) {
          console.log("上传错误", e);
          reject({ executed: false, message: "上传错误" });
        }
      };
      if (file.size > 1 * 1024 * 1024) {
        if (!basic) {
          basic = {
            q: 0.7
          };
        }
        //压缩图片
        Utils.gizpImg(file, basic, function(blob) {
          begin(blob);
        });
      } else {
        begin(file);
      }
    });
  },
  /**
   * 直接上传图片(blob)
   * @param blob 文件
   * @param config sts接口返回的信息
   * @param basic  压缩属性0-1 {w,h,q}
   */
  uploadBlobImage(blob, fileName, config) {
    let th = this;
    return new Promise(function(resolve, reject) {
      let str = th.getMaterials(fileName);
      let begin = async file => {
        let Obj = new AliOSS({
          //   region: "oss-cn-hangzhou",
          accessKeyId: config.accessKeyId,
          accessKeySecret: config.accessKeySecret,
          stsToken: config.securityToken,
          endpoint: "https://oss-cn-beijing.aliyuncs.com",
          bucket: config.bucket
        });
        try {
          let result = await Obj.put(str, file);
          resolve({
            executed: true,
            path: str
          });
        } catch (e) {
          console.log("上传错误", e);
          reject({ executed: false, message: "上传错误" });
        }
      };
      begin(blob);
    });
  }
};
export default OssFile;
